/*
 * $AIST_Release: 0.9.0 $
 * Copyright 2011 Information Technology Research Institute, National
 * Institute of Advanced Industrial Science and Technology
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *    http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package util

import java.io.File
import java.io.IOException
import java.lang.Runtime
import java.lang.Runnable
import scala.collection.mutable.ListBuffer
import scala.collection.JavaConversions._

/**
 * Utilities for file operations
 */
object FileUtils {

  private var registered = false;
  private val targetDirs = ListBuffer[File]()

  private object TempDirRemover extends Runnable {
    override def run() {
      FileUtils.this.synchronized {
        targetDirs.foreach(removeDirectoryForce)
      }
    }
  }

  def removeDirectoryForce(target: File): Unit = {
    if (target.isDirectory()) {
      target.list().foreach { x => removeDirectoryForce(new File(target, x)) }
    }
    target.delete()
  }

  /**
   * Creates temporary directory.
   *
   * @note The directory created by this function is not deleted at exit of process.
   */
  def createTempDir(remainAfterExit: Boolean): File = {
    this.synchronized {
      if (!registered) {
        Runtime.getRuntime().addShutdownHook(new Thread(TempDirRemover, "TempDirRemover")) 
        registered = true;
      }
      val tmp = File.createTempFile("sctmp", "d").getAbsoluteFile

      if(!tmp.delete()) {
        throw new IOException("Could not delete temp file: " + tmp.getAbsolutePath);
      }
      if(!tmp.mkdir()) {
        throw new IOException("Could not create temp directory: " + tmp.getAbsolutePath);
      }
      if (!remainAfterExit) {
        targetDirs.append(tmp)
      }
      return tmp
    }
  }

  /**
   * Closes the specified file at end of block.
   */
  def useFile[T <: {def close()}, U](file: T)(f: T => U) = {
    try {
      f(file)
    } finally {
      file.close()
    }
  }
}
